package framework
{
	import mx.rpc.AsyncToken;
	import mx.rpc.events.ResultEvent;
	
	public function handleData(asyncToken:AsyncToken, host:Object, property:String, transform:Function = null, faultHandler:Function = null):AsyncToken
	{
		function makeArray(obj:Object, prop:String, objToAdd:Object = null):Array
		{
			var array:Array = obj[prop] as Array;
			if (!array)
			{
				array = [];
				obj[prop] = array;
			}
			if (objToAdd)
			{
				array.push(objToAdd);
			}
			return array;
		}
		
		function handleDataHandler(e:ResultEvent):void
		{
			var r:* = e.result;
			var dataHandler:Object = e.token.__dataHandlers.shift();
			if (dataHandler.transform)
			{
				r = dataHandler.transform(r);
			}
			Utils.setProperty(dataHandler.property, dataHandler.host, r);
		}
		var dataHandler:Object = {};
		dataHandler.transform = transform;
		dataHandler.host = host;
		dataHandler.property = property;
		var handlers:Array = makeArray(asyncToken,"__dataHandlers");
		handlers.push(dataHandler);
		return handle(asyncToken, handleDataHandler, faultHandler);
	}
}